#include "IpcMqttClient.h"
#include "IpcMqttClientHandler.h"
#include "IpcMqttClientPublish.h"
#include "InSdkCheckNetStatus.h"

#define DEF_TAG             "IpcMqttClient"

mqtt_client_t *g_IpcMqtt_Client = NULL;

mqtt_client_t *Ext_Get_g_IpcMqtt_Client(void)
{
    return g_IpcMqtt_Client;
}

//int Ext_IpcMqttClient_Init(void)
int main(void)
{
    Com_s32 ret;
    StSdkNetStatusHostInfo host_info;

    memset(&host_info, 0, sizeof(host_info));
    mqtt_log_init();

    while (1)
    {
        char host[32];
        char port[32];

        memset(host, 0, sizeof(host));
        memset(port, 0, sizeof(port));

        strcpy(host,"192.168.1.88");
        strcpy(port,"1883");
        g_IpcMqtt_Client = mqtt_lease();

        mqtt_set_host(g_IpcMqtt_Client, host);
        mqtt_set_port(g_IpcMqtt_Client, port);

        if ((atoi(port) != host_info.port) || (strcmp(host_info.host, host) != 0))
        {
            memset(&host_info, 0, sizeof(host_info));
            host_info.port = atoi(port);
            strncpy(host_info.host, host, sizeof(host_info.host));
            PRT_DBG(DEF_TAG,"switch mqtt info\n");
        }

        ret = Ext_InSdkNetStatus_ConnectServerResult(&host_info);
        if(ret == DEF_COM_FAILED)
        {
            sleep(2);
            PRT_WARN(DEF_TAG,"connect %s:%s again\n",host, port);
            continue;
        }

        mqtt_set_client_id(g_IpcMqtt_Client, "zkkc250812");
        mqtt_set_user_name(g_IpcMqtt_Client, "admin");
        mqtt_set_password(g_IpcMqtt_Client, "admin");

        mqtt_set_clean_session(g_IpcMqtt_Client, 1);

        ret = mqtt_connect(g_IpcMqtt_Client);
        if (ret == MQTT_SUCCESS_ERROR)
        {
            // 初始化所有发布和订阅的主题
            Ext_IpcMqttCom_TopicInit();
            Ext_IpcMqttClientHandler_SubscribeInit(g_IpcMqtt_Client);

            mqtt_list_subscribe_topic(g_IpcMqtt_Client);
            Ext_IpcMqttClientPublish_PropertyPostFirst();
            break;
        }
        else
        {
            PRT_WARN(DEF_TAG,"mqtt restart\n");
            Ext_IpcMqttClient_Exit();
            sleep(1);
        }
    }

    return 0;
}

void Ext_IpcMqttClient_Exit(void)
{
    if (g_IpcMqtt_Client != NULL)
    {
        mqtt_disconnect(g_IpcMqtt_Client);
        mqtt_release(g_IpcMqtt_Client);
    }
}
